package com.sercomm.ott.mediaplayer;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * Created by davis on 17-9-30.
 */

public class ShowAppActivity extends Activity{
    private final static String TAG="ShowAppActivity";
    public static final String SCHEMA_APP_NAME = "[name]";
    public static final String SCHEMA_APP_PACK = "[pack]";
    public static final String SCHEMA_APP_ACTIVITY = "[activity]";
    public static final String SCHEMA_APP_ICON = "[icon]";
    public static final String GLOBAL_PACK_NAME = "com.sercomm.ott.mediaplayer";
    public static final int PAGE_APP_DEFAULT = 0;
    public static final int PAGE_APP_ADD = 1;
    public int page_app_mode = PAGE_APP_DEFAULT;

    public GridView page_app = null;
    private static final String[] SCHEMA_ARRAY = new String[]{
            SCHEMA_APP_NAME, SCHEMA_APP_ICON,
            SCHEMA_APP_PACK,SCHEMA_APP_ACTIVITY};
    private static final int[] RESOURCE_ARRAY = new int[]{
            R.id.page_app_name,R.id.page_app_icon};

    @Override
    public void onCreate(Bundle savaInstanceState){
        super.onCreate(savaInstanceState);
        setContentView(R.layout.show_app);
        page_app = (GridView)findViewById(R.id.page_app);
        initApplicationView();
    }
    public void initApplicationView(){
        updateAppAdapter();
        setFocusChangeListener();
        setItemSelectListener();
        setItemClickListener();
        setItemLongClickListener();
    }
    public void updateAppAdapter(){
        page_app.setAdapter(getAppItemAdapter());
    }
    private SimpleAdapter getAppItemAdapter(){
        // Get All App info : name, icon, package, mainActivity
        PackageManager pm = getPackageManager();
        ArrayList<HashMap<String,Object>> items = getAppItemList(pm);

        SimpleAdapter adapter = new SimpleAdapter(
                this, items, R.layout.show_app_item,
                SCHEMA_ARRAY, RESOURCE_ARRAY);

        // Directly Show Drawable icon
        adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
            @Override
            public boolean setViewValue(View view, Object o, String s) {
                if (view instanceof ImageView && o instanceof Drawable) {
                    ImageView iv = (ImageView) view;
                    iv.setImageDrawable((Drawable) o);
                    return true;
                }
                return false;
            }
        });

        return adapter;
    }

    private ArrayList<HashMap<String,Object>> getAppItemList(PackageManager pm){
        // Get All App info : name, icon, package, mainActivity
        List apps = getAppList(pm);
        ArrayList<HashMap<String,Object>> items = new ArrayList<>();
        for (Object obj : apps){
            ResolveInfo info = (ResolveInfo) obj;
            if (info.activityInfo.packageName.equals(GLOBAL_PACK_NAME))
                continue;
            HashMap<String,Object> map = new HashMap<>();
            map.put(SCHEMA_APP_NAME,info.loadLabel(pm).toString());
            map.put(SCHEMA_APP_ICON,info.loadIcon(pm));
            map.put(SCHEMA_APP_PACK,info.activityInfo.packageName);
            map.put(SCHEMA_APP_ACTIVITY,info.activityInfo.name);
            items.add(map);
        }

        // For test long app name, display marquee
        /*
        HashMap<String,Object> map = new HashMap<>();
        map.put(SCHEMA_NAME,"This is a test Application name");
        map.put(SCHEMA_ICON,null);
        map.put(SCHEMA_PACK,"");
        items.add(map);
        */

        return items;
    }

    public static List getAppList(PackageManager pm){
        // Get All App list
        Intent main = new Intent(Intent.ACTION_MAIN,null);
        main.addCategory(Intent.CATEGORY_LAUNCHER);

        List apps = pm.queryIntentActivities(main,0);
        Collections.sort(apps,new ResolveInfo.DisplayNameComparator(pm));

        return apps;
    }

    private void setItemSelectListener(){
        // show app count and position
            page_app.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                //launcher.switcher_right.setText(""+(i+1)+" / "+launcher.page_app.getCount());
                ViewCompat.animate(view).scaleX(1.1f).scaleY(1.1f).translationZ(1.1f).start();
                for(int j = 0;j<adapterView.getCount();j++){
                    if(j==i) continue;
                    ViewCompat.animate(adapterView.getChildAt(j)).scaleX(1).scaleY(1).translationZ(1).start();
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                //launcher.switcher_right.setText("1 / "+launcher.page_app.getCount());
            }
        });
    }


    private void setFocusChangeListener(){
        // show app count and position
            page_app.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b){
                    //launcher.switcher_right.setText(
                            //""+(launcher.page_app.getSelectedItemPosition()+1)
                                    //+" / "+launcher.page_app.getCount());
                }
                else{
                    //launcher.switcher_right.setText(""+launcher.page_app.getCount());
                }
            }
        });
    }

    private void setItemClickListener(){
                page_app.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapter, View view, int i, long l) {
                HashMap item = (HashMap) adapter.getItemAtPosition(i);
                String name = (String) item.get(SCHEMA_APP_NAME);
                String pack = (String) item.get(SCHEMA_APP_PACK);
                String activity = (String) item.get(SCHEMA_APP_ACTIVITY);
                Log.d(TAG,"GridView Click App name : " + name
                        + " , package : " + pack
                        + " , main activity : " + activity);
                if (page_app_mode == PAGE_APP_DEFAULT) {
                    // start this app
                    Intent app = new Intent(Intent.ACTION_MAIN);
                    app.addCategory(Intent.CATEGORY_LAUNCHER);
                    app.setComponent(new ComponentName(pack, activity));
                    startActivity(app);
                }
                else if (page_app_mode == PAGE_APP_ADD){
                    // Add app link to shortcut line
                    //SLauncher.log("Add app "+name+", pack : "+pack+" to link");
                    //ShortcutFactory.addShortcutItem(launcher,item);
                }
            }
        });
    }

    private void setItemLongClickListener(){
                page_app.setOnItemLongClickListener(
                new AdapterView.OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(AdapterView<?> adapter, View view, int i, long l) {
                        HashMap item = (HashMap) adapter.getItemAtPosition(i);
                        String name = (String) item.get(SCHEMA_APP_NAME);
                        String pack = (String) item.get(SCHEMA_APP_PACK);
                        String activity = (String) item.get(SCHEMA_APP_ACTIVITY);
                        Log.d(TAG,"GridView Long Click App name : " + name
                                + " , package : " + pack
                                + " , main activity : " + activity);
                        if (page_app_mode == PAGE_APP_DEFAULT) {
                            // uninstall this app
                            Uri uri = Uri.parse("package:" + pack);
                            Intent del = new Intent(Intent.ACTION_DELETE, uri);
                            startActivity(del);
                        }
                        return true;
                    }
                });
    }

    @Override
    protected void onResume(){
        super.onResume();
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
    }

}
